/**
 * Copyright 2008 by Robert Konigsberg
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the same terms as Perl.
 *
 * @see http://www.perl.com/perl/misc/Artistic.html
 */
package visitor.client;

import visitor.maze.Direction;
import visitor.maze.Maze;
import visitor.maze.Room;

public class IterativeWalkerMain {

  private static class Position {
    private final Room room;
    private final Direction heading;

    public Position(Room room, Direction facing) {
      this.heading = facing;
      this.room = room;
    }
  };

  private Position start;
  private Position current;

  private Room destination;

  public IterativeWalkerMain(Maze maze, int start, int end, Direction facing) {
    this.start = new Position(maze.getRoom(start), facing);
    this.destination = maze.getRoom(end);
  }

  public void go() {
    current = start;
    System.out.println(current);
    while (current.room != destination) {

      Direction nextDirection = findNextDirection();
      Room nextRoom = current.room.getExit(nextDirection);

      setState(nextDirection, nextRoom);
    }
  }

  private Direction findNextDirection() {
    Direction oppositeDirection = current.heading.opposite();
    Direction nextDirection = oppositeDirection.right();
    while (nextDirection != oppositeDirection) {
      Room r = current.room.getExit(nextDirection);
      if (r != null) {
        return nextDirection;
      }
      nextDirection = nextDirection.right();
    }
    return oppositeDirection;
  }

  private void setState(Direction direction, Room room) {
    System.out.printf("Turning %s to enter %s\n", direction, room);
    current = new Position(room, direction);
  }

  public static void main(String[] args) {
    Maze maze = Mazes.getFirstMaze();
    new IterativeWalkerMain(maze, 1, 4, Direction.NORTH).go();
  }
}
